<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>UIKit与swiftUI 交互 | 路漫漫其修远兮，吾将上下而求索</title><meta name="keywords" content="swift,swiftUI"><meta name="author" content="Charles Yan"><meta name="copyright" content="Charles Yan"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="swiftUI 写界面太舒服了，但是毕竟是新生的东西，还不能完全替代uikit，这时就需要考虑到uikit与swiftUI交互了。">
<meta property="og:type" content="article">
<meta property="og:title" content="UIKit与swiftUI 交互">
<meta property="og:url" content="https://www.charlesyan.cn/2020/02/09/swiftui%E4%B8%8Euikit%E4%BA%A4%E4%BA%92/index.html">
<meta property="og:site_name" content="路漫漫其修远兮，吾将上下而求索">
<meta property="og:description" content="swiftUI 写界面太舒服了，但是毕竟是新生的东西，还不能完全替代uikit，这时就需要考虑到uikit与swiftUI交互了。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200113121716232.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1Zpc3RvcnNZYW4=,size_16,color_FFFFFF,t_70">
<meta property="article:published_time" content="2020-02-08T16:00:00.000Z">
<meta property="article:modified_time" content="2020-02-10T02:26:14.661Z">
<meta property="article:author" content="Charles Yan">
<meta property="article:tag" content="swift">
<meta property="article:tag" content="swiftUI">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20200113121716232.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1Zpc3RvcnNZYW4=,size_16,color_FFFFFF,t_70"><link rel="shortcut icon" href="/img/favicon.ico"><link rel="canonical" href="https://www.charlesyan.cn/2020/02/09/swiftui%E4%B8%8Euikit%E4%BA%A4%E4%BA%92/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'mediumZoom',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'UIKit与swiftUI 交互',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2020-02-10 10:26:14'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><link rel="stylesheet" href="/css/selfdesign.css" media="defer" onload="this.media='all'"><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="/img/My%20avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">37</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">22</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">12</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-coffee"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-list"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fa fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fa fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://img-blog.csdnimg.cn/20200113121716232.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1Zpc3RvcnNZYW4=,size_16,color_FFFFFF,t_70')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">路漫漫其修远兮，吾将上下而求索</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-coffee"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-list"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fa fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fa fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">UIKit与swiftUI 交互</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-02-08T16:00:00.000Z" title="发表于 2020-02-09 00:00:00">2020-02-09</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2020-02-10T02:26:14.661Z" title="更新于 2020-02-10 10:26:14">2020-02-10</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/IOS%E5%BC%80%E5%8F%91/">IOS开发</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">451</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>1分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="UIKit与swiftUI 交互"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="UIKit与swiftUI-交互"><a href="#UIKit与swiftUI-交互" class="headerlink" title="UIKit与swiftUI 交互"></a>UIKit与swiftUI 交互</h1><p>运用swiftUI写界面非常迅速且酷炫。大大减少了曾经在UIKit中的代码量。<br>不过有时候可能你还会需要用到UIKit，但是你又想用swiftUI做界面，此时就考虑到二者交互的问题了。</p>
<h2 id="UIViewControllerRepresentable"><a href="#UIViewControllerRepresentable" class="headerlink" title="UIViewControllerRepresentable"></a>UIViewControllerRepresentable</h2><p><strong>在swiftUI中提供了一个UIViewControllerRepresentable协议</strong><br><strong>我们可以用它作为UIKit 与swiftUI的桥接</strong><br><img src="https://img-blog.csdnimg.cn/20200113121716232.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1Zpc3RvcnNZYW4=,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<h1 id="第一步："><a href="#第一步：" class="headerlink" title="第一步："></a>第一步：</h1><h2 id="你依然可以像往常一样，新建一个swift文件，把他命名为viewController-然后导入UiKit-，然后再让它继承UIViewController-重写父类的viewDidLoad-方法，你也可以往里面随便添点东西，为后面验证做准备，just-like-this"><a href="#你依然可以像往常一样，新建一个swift文件，把他命名为viewController-然后导入UiKit-，然后再让它继承UIViewController-重写父类的viewDidLoad-方法，你也可以往里面随便添点东西，为后面验证做准备，just-like-this" class="headerlink" title="你依然可以像往常一样，新建一个swift文件，把他命名为viewController 然后导入UiKit ，然后再让它继承UIViewController 重写父类的viewDidLoad()方法，你也可以往里面随便添点东西，为后面验证做准备，just like this.."></a>你依然可以像往常一样，新建一个swift文件，把他命名为viewController 然后导入UiKit ，然后再让它继承UIViewController 重写父类的viewDidLoad()方法，你也可以往里面随便添点东西，为后面验证做准备，just like this..<img src="https://img-blog.csdnimg.cn/20200113122152672.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1Zpc3RvcnNZYW4=,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></h2><h1 id="第二步-桥接"><a href="#第二步-桥接" class="headerlink" title="第二步 桥接"></a>第二步 桥接</h1><h2 id="第二步就是在你的swiftUI文件中写一个结构体连接你刚创建的viewController-他需要遵循并实现UIViewControllerRepresentable这个协议"><a href="#第二步就是在你的swiftUI文件中写一个结构体连接你刚创建的viewController-他需要遵循并实现UIViewControllerRepresentable这个协议" class="headerlink" title="第二步就是在你的swiftUI文件中写一个结构体连接你刚创建的viewController 他需要遵循并实现UIViewControllerRepresentable这个协议"></a>第二步就是在你的swiftUI文件中写一个结构体连接你刚创建的viewController 他需要遵循并实现UIViewControllerRepresentable这个协议</h2><h1 id="第三步-应用"><a href="#第三步-应用" class="headerlink" title="第三步 应用"></a>第三步 应用</h1><h2 id="接下来直接在你swiftUI中结构体中调用第二步的结构体就OK了"><a href="#接下来直接在你swiftUI中结构体中调用第二步的结构体就OK了" class="headerlink" title="接下来直接在你swiftUI中结构体中调用第二步的结构体就OK了"></a>接下来直接在你swiftUI中结构体中调用第二步的结构体就OK了<img src="https://img-blog.csdnimg.cn/20200113125213490.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1Zpc3RvcnNZYW4=,size_16,color_FFFFFF,t_70" alt="第二步与第三步"></h2><h1 id="显示效果如图"><a href="#显示效果如图" class="headerlink" title="显示效果如图"></a>显示效果如图</h1><p><img src="https://img-blog.csdnimg.cn/20200113130421611.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1Zpc3RvcnNZYW4=,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<h1 id="代码如下："><a href="#代码如下：" class="headerlink" title="代码如下："></a>代码如下：</h1><p>viewController.swift 文件中：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Foundation</span><br><span class="line"><span class="keyword">import</span> UIKit</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">viewController</span>: <span class="title">UIViewController</span></span>&#123;</span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">viewDidLoad</span>()</span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.viewDidLoad()</span><br><span class="line">        <span class="keyword">self</span>.view.backgroundColor <span class="operator">=</span> .brown</span><br><span class="line">        <span class="keyword">let</span> viewDemo <span class="operator">=</span> <span class="type">UIView</span>(frame: <span class="type">CGRect</span>(x: <span class="number">100</span>, y: <span class="number">100</span>, width: <span class="number">100</span>, height: <span class="number">100</span>))</span><br><span class="line">        viewDemo.backgroundColor <span class="operator">=</span> .green</span><br><span class="line">        <span class="keyword">self</span>.view.addSubview(viewDemo)</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>ConventView.swift 文件中</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//UIKit 桥接</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">UIBridging</span>: <span class="title">UIViewControllerRepresentable</span> </span>&#123;</span><br><span class="line">    <span class="comment">//这个UIViewControllerType你要接哪个就是哪个，在这里就是viewController</span></span><br><span class="line">    <span class="keyword">typealias</span> <span class="type">UIViewControllerType</span> <span class="operator">=</span> viewController</span><br><span class="line">    <span class="comment">//必须实现的方法，当swiftUI要显示view时，会调用这个方法。返回值就是当前需要显示的类</span></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">makeUIViewController</span>(<span class="params">context</span>: <span class="type">UIViewControllerRepresentableContext</span>&lt;<span class="type">UIBridging</span>&gt;)</span> -&gt; <span class="type">UIBridging</span>.<span class="type">UIViewControllerType</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> viewController()</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//更新UIViewController时会调用此方法</span></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">updateUIViewController</span>(<span class="keyword">_</span> <span class="params">uiViewController</span>: viewController, <span class="params">context</span>: <span class="type">UIViewControllerRepresentableContext</span>&lt;<span class="type">UIBridging</span>&gt;)</span> &#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ContentView</span>: <span class="title">View</span></span>&#123;</span><br><span class="line">    <span class="keyword">var</span> body: <span class="keyword">some</span> <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">UIBridging</span>()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ContentView_Previews</span>: <span class="title">PreviewProvider</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">var</span> previews: <span class="keyword">some</span> <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">ContentView</span>()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h2 id="注：你也可以写在一个文件中，但后期为了看着方便，简洁，还是分开写比较好一些"><a href="#注：你也可以写在一个文件中，但后期为了看着方便，简洁，还是分开写比较好一些" class="headerlink" title="注：你也可以写在一个文件中，但后期为了看着方便，简洁，还是分开写比较好一些"></a>注：你也可以写在一个文件中，但后期为了看着方便，简洁，还是分开写比较好一些</h2></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Charles Yan</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://www.charlesyan.cn/2020/02/09/swiftui%E4%B8%8Euikit%E4%BA%A4%E4%BA%92/">https://www.charlesyan.cn/2020/02/09/swiftui%E4%B8%8Euikit%E4%BA%A4%E4%BA%92/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://www.charlesyan.cn" target="_blank">路漫漫其修远兮，吾将上下而求索</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/swift/">swift</a><a class="post-meta__tags" href="/tags/swiftUI/">swiftUI</a></div><div class="post_share"><div class="social-share" data-image="https://img-blog.csdnimg.cn/20200113121716232.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1Zpc3RvcnNZYW4=,size_16,color_FFFFFF,t_70" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/IMG_0003.jpeg" target="_blank"><img class="post-qr-code-img" src="/img/IMG_0003.jpeg" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li><li class="reward-item"><a href="/img/IMG_0004.jpeg" target="_blank"><img class="post-qr-code-img" src="/img/IMG_0004.jpeg" alt="alipay"/></a><div class="post-qr-code-desc">alipay</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2020/02/12/word%E4%B8%AD%E5%A6%82%E4%BD%95%E5%8A%A0%E5%85%A5%E5%B8%A6%E2%88%9A%E7%9A%84%E5%B0%8F%E6%96%B9%E5%9D%97/"><img class="prev-cover" src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1214975356,507844605&amp;fm=26&amp;gp=0.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">word中如何加入带√的□ ?</div></div></a></div><div class="next-post pull-right"><a href="/2020/02/07/Codeblocks%E4%B8%AD%E6%96%87%E4%B9%B1%E7%A0%81%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95/"><img class="next-cover" src="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3759108711,423074118&amp;fm=26&amp;gp=0.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Codeblocks中文乱码解决方法</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2020/01/30/swift基本运算符/" title="swift之基本运算符"><img class="cover" src="http://img4.imgtn.bdimg.com/it/u=3068490346,2026640014&fm=26&gp=0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-01-30</div><div class="title">swift之基本运算符</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#UIKit%E4%B8%8EswiftUI-%E4%BA%A4%E4%BA%92"><span class="toc-number">1.</span> <span class="toc-text">UIKit与swiftUI 交互</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#UIViewControllerRepresentable"><span class="toc-number">1.1.</span> <span class="toc-text">UIViewControllerRepresentable</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC%E4%B8%80%E6%AD%A5%EF%BC%9A"><span class="toc-number">2.</span> <span class="toc-text">第一步：</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%A0%E4%BE%9D%E7%84%B6%E5%8F%AF%E4%BB%A5%E5%83%8F%E5%BE%80%E5%B8%B8%E4%B8%80%E6%A0%B7%EF%BC%8C%E6%96%B0%E5%BB%BA%E4%B8%80%E4%B8%AAswift%E6%96%87%E4%BB%B6%EF%BC%8C%E6%8A%8A%E4%BB%96%E5%91%BD%E5%90%8D%E4%B8%BAviewController-%E7%84%B6%E5%90%8E%E5%AF%BC%E5%85%A5UiKit-%EF%BC%8C%E7%84%B6%E5%90%8E%E5%86%8D%E8%AE%A9%E5%AE%83%E7%BB%A7%E6%89%BFUIViewController-%E9%87%8D%E5%86%99%E7%88%B6%E7%B1%BB%E7%9A%84viewDidLoad-%E6%96%B9%E6%B3%95%EF%BC%8C%E4%BD%A0%E4%B9%9F%E5%8F%AF%E4%BB%A5%E5%BE%80%E9%87%8C%E9%9D%A2%E9%9A%8F%E4%BE%BF%E6%B7%BB%E7%82%B9%E4%B8%9C%E8%A5%BF%EF%BC%8C%E4%B8%BA%E5%90%8E%E9%9D%A2%E9%AA%8C%E8%AF%81%E5%81%9A%E5%87%86%E5%A4%87%EF%BC%8Cjust-like-this"><span class="toc-number">2.1.</span> <span class="toc-text">你依然可以像往常一样，新建一个swift文件，把他命名为viewController 然后导入UiKit ，然后再让它继承UIViewController 重写父类的viewDidLoad()方法，你也可以往里面随便添点东西，为后面验证做准备，just like this..</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC%E4%BA%8C%E6%AD%A5-%E6%A1%A5%E6%8E%A5"><span class="toc-number">3.</span> <span class="toc-text">第二步 桥接</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC%E4%BA%8C%E6%AD%A5%E5%B0%B1%E6%98%AF%E5%9C%A8%E4%BD%A0%E7%9A%84swiftUI%E6%96%87%E4%BB%B6%E4%B8%AD%E5%86%99%E4%B8%80%E4%B8%AA%E7%BB%93%E6%9E%84%E4%BD%93%E8%BF%9E%E6%8E%A5%E4%BD%A0%E5%88%9A%E5%88%9B%E5%BB%BA%E7%9A%84viewController-%E4%BB%96%E9%9C%80%E8%A6%81%E9%81%B5%E5%BE%AA%E5%B9%B6%E5%AE%9E%E7%8E%B0UIViewControllerRepresentable%E8%BF%99%E4%B8%AA%E5%8D%8F%E8%AE%AE"><span class="toc-number">3.1.</span> <span class="toc-text">第二步就是在你的swiftUI文件中写一个结构体连接你刚创建的viewController 他需要遵循并实现UIViewControllerRepresentable这个协议</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC%E4%B8%89%E6%AD%A5-%E5%BA%94%E7%94%A8"><span class="toc-number">4.</span> <span class="toc-text">第三步 应用</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8E%A5%E4%B8%8B%E6%9D%A5%E7%9B%B4%E6%8E%A5%E5%9C%A8%E4%BD%A0swiftUI%E4%B8%AD%E7%BB%93%E6%9E%84%E4%BD%93%E4%B8%AD%E8%B0%83%E7%94%A8%E7%AC%AC%E4%BA%8C%E6%AD%A5%E7%9A%84%E7%BB%93%E6%9E%84%E4%BD%93%E5%B0%B1OK%E4%BA%86"><span class="toc-number">4.1.</span> <span class="toc-text">接下来直接在你swiftUI中结构体中调用第二步的结构体就OK了</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%98%BE%E7%A4%BA%E6%95%88%E6%9E%9C%E5%A6%82%E5%9B%BE"><span class="toc-number">5.</span> <span class="toc-text">显示效果如图</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E5%A6%82%E4%B8%8B%EF%BC%9A"><span class="toc-number">6.</span> <span class="toc-text">代码如下：</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B3%A8%EF%BC%9A%E4%BD%A0%E4%B9%9F%E5%8F%AF%E4%BB%A5%E5%86%99%E5%9C%A8%E4%B8%80%E4%B8%AA%E6%96%87%E4%BB%B6%E4%B8%AD%EF%BC%8C%E4%BD%86%E5%90%8E%E6%9C%9F%E4%B8%BA%E4%BA%86%E7%9C%8B%E7%9D%80%E6%96%B9%E4%BE%BF%EF%BC%8C%E7%AE%80%E6%B4%81%EF%BC%8C%E8%BF%98%E6%98%AF%E5%88%86%E5%BC%80%E5%86%99%E6%AF%94%E8%BE%83%E5%A5%BD%E4%B8%80%E4%BA%9B"><span class="toc-number">6.1.</span> <span class="toc-text">注：你也可以写在一个文件中，但后期为了看着方便，简洁，还是分开写比较好一些</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer" style="background-image: url('https://img-blog.csdnimg.cn/20200113121716232.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1Zpc3RvcnNZYW4=,size_16,color_FFFFFF,t_70')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By Charles Yan</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcome to my <a target="_blank" rel="noopener" href="https:charlesyan.cn/">blog</a>!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="rightside.chat_btn"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>(()=>{
  const $countDom = document.getElementById('twikoo-count')
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'https://twikoo-beta-tawny.vercel.app/',
      region: ''
    }, null))
  }

  const getCount = () => {
    twikoo.getCommentsCount({
      envId: 'https://twikoo-beta-tawny.vercel.app/',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      $countDom.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const loadTwikoo = (bool = false) => {
    if (typeof twikoo === 'object') {
      init()
      bool && $countDom && setTimeout(getCount,0)
    } else {
      getScript('https://cdn.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(()=> {
        init()
        bool && $countDom && setTimeout(getCount,0)
      })
    }
  }

  if ('Twikoo' === 'Twikoo' || !false) {
    if (false) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo(true)
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>